package backtracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/25 23:10
 * https://leetcode-cn.com/problems/palindrome-partitioning/
 */
public class Partition {

    static List<List<String>> result;
    static LinkedList<String> list;

    public List<List<String>> partition(String s) {
        result = new ArrayList<>();
        list = new LinkedList<>();
        backTracking(0, s);
        return result;
    }

    /**
     * 切法：切1 - s.length
     * @param start 开始切割的位置
     * @param s
     */
    public static void backTracking(int start, String s) {
        if (start >= s.length()) {
            result.add(new ArrayList<>(list));
            return;
        }
        for (int i = start; i < s.length() ; i++) {
            //获取[start, i]在String s中的子串  i-start 代表截取的长度，之后每次i++
            if (isPalindrome(s, start, i)) {
                String substring = s.substring(start, i + 1);
                list.add(substring);
            } else {
                //每个子串必须为回文串
                continue;
            }
            //每次截取的起点后移
            backTracking(i + 1, s);
            list.removeLast();
        }
    }

    public static boolean isPalindrome(String s, int i, int j) {
        for (; i < j; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {

    }
}
